package com.ccp.dev.system.service;

import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.JSONObjectUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.model.FileManagement;
import com.ccp.dev.system.model.Position;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;


/**
 * 权限信息服务类
 *
 * @author zhaowj
 * @date 2020-03-22 14:11:51
 */
@Service
public class RightManageService {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private PositionService positionService;

    @Resource
    private SysOrgService sysOrgService;

    /**权限类型（管理）=4*/
    public static final  int RIGHT_TYPE_MANAGE =4;

    /**
     * 判断是否有显示权限
     *
     * @param nodeID         当前节点id
     * @param permissionJson 权限JSON串
     * @return
     */
    public Boolean checkNodeRight(String nodeID, String permissionJson) {
        if (StringUtils.isEmpty(permissionJson)) {
            return false;
        }
        Map<String, Object> rightMap = getRightMap(ContextUtil.getCurrentUser().getUserId(), ContextUtil.getCurrentOrgId());
        Map<String, Boolean> managePermission = getManagePermission(RIGHT_TYPE_MANAGE, permissionJson, rightMap);
        if (managePermission.get(String.valueOf(nodeID)) == null || managePermission.get(String.valueOf(nodeID))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取当前用户的权限Map
     * Map其实就是包括：用户的角色、岗位、组织、可管理组织列表
     *
     * @param userId
     * @param curOrgId
     * @return
     */
    public Map<String, Object> getRightMap(String userId, String curOrgId) {
        Map<String, Object> map = new HashMap<>(16);
        List<SysRole> roles = sysRoleService.queryByUserId(userId);
        List<Position> positions = positionService.queryByUserId(userId);
        SysOrg org = sysOrgService.getOrgByUserId(userId);
        map.put("userId", userId);
        map.put("curOrgId", curOrgId);
        map.put("roles", roles);
        map.put("positions", positions);
        map.put("orgs", org);
        return map;
    }

    /**
     * 获取管理的权限
     *
     * @param type
     * @param manageField
     * @param rightMap
     * @return
     */
    public Map<String, Boolean> getManagePermission(int type, String manageField, Map<String, Object> rightMap) {
        if (StringUtils.isEmpty(manageField)) {
            return null;
        }
        JSONArray jsonAry = JSONArray.fromObject(manageField);
        return getPermissionMap(type, jsonAry, rightMap);
    }


    /**
     * 获取权限map
     *
     * @param type
     * @param jsonAry
     * @param rightMap
     * @return
     */
    public static Map<String, Boolean> getPermissionMap(int type, JSONArray jsonAry, Map<String, Object> rightMap) {
        Map<String, Boolean> map = new HashMap<>(16);
        if (JSONObjectUtil.isEmpty(jsonAry)) {
            return map;
        }

        for (Object obj : jsonAry) {
            JSONObject json = JSONObject.fromObject(obj);
            String var = getRightsName(json);
            JSONArray rights = (JSONArray) json.get("right");
            Iterator<JSONObject> iterator = rights.iterator();
            boolean hasRight = false;
            while (true) {
                JSONObject permission = iterator.next();
                Integer s = (Integer) permission.get("s");
                if (s == null || s.intValue() == type && permission.containsKey("type")) {
                    hasRight = hasRight(permission, rightMap);
                    if (hasRight) {
                        map.put(var, hasRight);
                        break;
                    }
                }
                if (!iterator.hasNext()) {
                    map.put(var, hasRight);
                    break;
                }
            }
        }
        return map;
    }

    public static String getRightsName(JSONObject json){
        String var = (String) json.get("variable");
        if(StringUtil.isEmpty(var)) {
            var = json.getString("name");
        }
        return var;
    }

    /**
     * 判断是否有权限。
     *
     * @param permission
     * @param rightMap   权限map
     * @return
     */
    public static boolean hasRight(JSONObject permission, Map<String, Object> rightMap) {
        String type = permission.get("type").toString();
        Object script = permission.get("script");
        // 无
        if ("none".equals(type)) {
            return false;
        }
        // 所有人
        if ("everyone".equals(type)) {
            return true;
        }
        String id = "";
        if (permission.containsKey("ids")) {
            id = permission.get("ids").toString();
        }
        String[] userId = null;
        String[] curOrgId = null;
        if (BeanUtils.isNotEmpty(rightMap.get("userId"))) {
            userId = rightMap.get("userId").toString().split(",");
        }
        if (BeanUtils.isNotEmpty(rightMap.get("curOrgId"))) {
            curOrgId = rightMap.get("curOrgId").toString().split(",");
        }

        List<SysRole> roles = (List<SysRole>) rightMap.get("roles");
        List<Position> positions = (List<Position>) rightMap.get("positions");
        SysOrg orgs = (SysOrg) rightMap.get("orgs");
        // 指定用户
        if ("user".equals(type)) {
            if (BeanUtils.isNotEmpty(userId)) {
                for (String ui : userId) {
                    return StringUtil.contain(id, ui);
                }
            }
        }
        // 指定角色
        else if ("role".equals(type)) {
            if (BeanUtils.isNotEmpty(roles)) {
                for (SysRole role : roles) {
                    if (StringUtil.contain(id, role.getRoleId())) {
                        return true;
                    }
                }
            }
        }
        else if ("org".equals(type)) {
            if (BeanUtils.isNotEmpty(orgs)) {
                if (StringUtil.contain(id, orgs.getOrgId())) {
                    return true;
                }
            }
        }
        // 岗位
        else if ("pos".equals(type)) {
            if (BeanUtils.isNotEmpty(positions)) {
                for (Position position : positions) {
                    if (StringUtil.contain(id, position.getPosId())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
